


from apscheduler.schedulers.background import BackgroundScheduler
from django_apscheduler.jobstores import DjangoJobStore, register_events, register_job

from django.conf import settings
from .kc_views.get_product import RefreshDataProduct
from apps.ipo.kc_views.kc_process import res_nets

""" 独立进程导入模型 """
from django.apps import apps
Feature = apps.get_model('ipo', 'Feature')
JSTOpenImage = apps.get_model('ipo', 'JSTOpenImage')

print('触发 django-apscheduler 定时任务.')


# 实例化调度器
scheduler = BackgroundScheduler()
# 调度器使用默认的DjangoJobStore()
scheduler.add_jobstore(DjangoJobStore(), 'default')


""" 每天0点执行【从聚水潭获取产品信息并保存在数据库】任务 """
@register_job(scheduler, 'cron', id='kendrick_apscheduler', hour=0, replace_existing=True)
def get_product_refresh():

    print('触发 django-apscheduler 定时任务...')

    # 从聚水潭获取产品信息并保存在数据库
    RefreshDataProduct()

    # 本地图像路径
    target_image_paths = [f'{settings.MEDIA_ROOT}/{item["paths"].split("/")[-1]}' for item in JSTOpenImage.objects.all().values('paths')]
    # 提取目标图片特征
    for item in ['ResNet101', 'ResNet50']:
        res_nets(item, target_image_paths)


# 注册定时任务并开始
def start():
    register_events(scheduler)
    scheduler.start()